﻿using AutoMapper;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Read.Apilication.Common.Province;
using B.S.BasicData.Read.DTOS;
using MediatR;

namespace B.S.BasicData.Read.Apilication.Handler.Province
{
    public class GetprovinceHandler : IRequestHandler<GetprovinceCommon, ApiResult<List<ProvinceDTO>>>
    {
        private readonly IBaseRepository<ProvinceModel> provinceRepo;
        private readonly IMapper mapper;

        public GetprovinceHandler(IBaseRepository<ProvinceModel> provinceRepo,IMapper mapper)
        {
            this.provinceRepo = provinceRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<List<ProvinceDTO>>> Handle(GetprovinceCommon request, CancellationToken cancellationToken)
        {
            ApiResult<List<ProvinceDTO>> res = new ApiResult<List<ProvinceDTO>>();

            res.Message = "树形结果查询成功";
            res.Code = ApiEnum.Success;
            res.Data = gettree(0);
            return Task.FromResult(res);

        }

        private List<ProvinceDTO> gettree(int parentid)
        {
            var info = provinceRepo.GetAll().Where(x=>x.ParintId==parentid).ToList();
            var model=mapper.Map<List<ProvinceDTO>>(info);
            foreach (var item in model)
            {
                item.Children = gettree(item.provinceId);
            }
            return model;

        }
    }
}
